package cn.edu.nju.bankaccount.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.nju.bankaccount.business.BankCustomer;
import cn.edu.nju.bankaccount.dao.impl.AccountDaoImpl;
import cn.edu.nju.bankaccount.factory.DaoFactory;
import cn.edu.nju.bankaccount.model.Account;

public class ShowBalance extends HttpServlet {

	private String accountNum;

	public String getAccountNum() {
		return accountNum;
	}

	public void setAccountNum(String accountNum) {
		this.accountNum = accountNum;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	private void processRequest(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		ServletContext context = getServletContext();
		BankCustomer bankCustomer = new BankCustomer();
		accountNum = req.getParameter("accountNum");
		Account a = DaoFactory.getAccountDao().findByAccountNum(accountNum);
		BankCustomer customer = null;
		System.out.println(a);
		if (a != null && a.getUser() != null) {
			customer = new BankCustomer();
			customer.setAccountNum(a.getAccountNum());
			customer.setFirstName(a.getUser().getUsername());
			customer.setMoney(a.getMoney());
		}
		try {
			String address = null;
			if (customer == null) {
				address = "/account/noAccount.jsp";
			} else {
				req.setAttribute("customer", customer);
				if (customer.getMoney() < 0) {
					address = "/account/negativeAccount.jsp";
				} else if (customer.getMoney() > 100000) {
					address = "/account/showAccountWithAd.jsp";
				} else
					address = "/account/showAccount.jsp";
			}
			context.getRequestDispatcher(address).forward(
					req, resp);
		} catch (ServletException e) {
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
					"This is a ServletException.");
		}

	}

}
